<template>
  <div class="app-container">
    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-input v-model="listQuery.cardNo" clearable class="filter-item" style="width: 200px;" placeholder="请输入会员卡号" />
      <el-select
        v-model="listQuery.cardStatus"
        clearable
        style="width: 200px"
        class="filter-item"
        placeholder="请选择会员卡状态">
        <el-option v-for="(key,index) in cardStatusMap" :key="index" :label="key.name" :value="key.value" />
      </el-select>
      <el-input v-model="listQuery.pageNo" clearable class="filter-item" style="width: 200px;" placeholder="请输入页码" />
      <el-button
        v-permission="['promote:usercard:query']"
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >查找</el-button>
      <el-button
        v-permission="['promote:usercard:query']"
        class="filter-item"
        type="primary"
        @click="previousPage"
      >上一页</el-button>
      <el-button
        v-permission="['promote:usercard:query']"
        class="filter-item"
        type="primary"
        @click="nextPage"
      >下一页</el-button>
      <div class="right-items" style="float: right;">
        <el-button
          class="filter-item"
          type="primary"
          icon="el-icon-search"
          @click="cardBatchWindow()"
        >批量操作</el-button>
        <el-button
          v-permission="['promote:usercard:query']"
          class="filter-item"
          type="primary"
          icon="el-icon-search"
          @click="downExcelBtn"
        >导出</el-button>
      </div>
    </div>

    <!-- 查询结果 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      size="small"
      element-loading-text="正在查询中。。。"
      border
      fit
      highlight-current-row
      style="white-space: pre-line"
    >
      <el-table-column prop="cardNo" align="center" label="卡片编号"/>
      <el-table-column prop="title" align="center" label="卡名称"/>
      <el-table-column prop="cardSecret" align="center" label="卡密">
        <template slot-scope="scope">******</template>
      </el-table-column>
      <el-table-column align="center" label="状态" prop="status">
        <template slot-scope="scope">
          <el-tag> {{ scope.row.status | formatStatus }} </el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" width="80" label="创建时间" prop="gmtCreate">
        <template slot-scope="scope">{{ scope.row.gmtCreate | formatTime }}</template>
      </el-table-column>
      <el-table-column prop="money" align="center" label="面值"/>
      <el-table-column prop="storeName" width="160" align="center" label="门店"/>
      <el-table-column prop="userId" align="center" label="用户ID"/>
      <el-table-column prop="userName" align="center" label="用户名称"/>
      <el-table-column prop="phone" align="center" label="手机号"/>
      <el-table-column align="center" label="操作" width="400" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-permission="['promote:usercard:update']"
            v-if="(scope.row.userId == null || scope.row.userId === 0)"
            type="primary"
            size="mini"
            @click="handleUpdate(scope.row)"
          >绑定</el-button>
          <el-button
            v-permission="['promote:usercard:query']"
            v-if="scope.row.status === 0 "
            type="danger"
            size="mini"
            style="width:80px"
            @click="openActivation(scope.row)"
          >匿名激活</el-button>
          <el-button
            v-permission="['promote:usercard:query']"
            v-if="scope.row.status === 0 "
            type="danger"
            size="mini"
            style="width:80px"
            @click="updateMoneyAlert(scope.row)"
          >编辑</el-button>
          <el-button
            v-permission="['promote:usercard:query']"
            type="danger"
            size="mini"
            style="width:80px"
            @click="handleShow(scope.row)"
          >查看卡密</el-button>
          <!--<el-button
            v-permission="['promote:usercard:delete']"
            type="danger"
            size="mini"
            @click="handleDelete(scope.row)"
          >删除</el-button>-->
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.pageNo"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <!-- 添加或修改对话框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="dataForm"
        status-icon
        label-position="left"
        label-width="100px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="编号" prop="id">
          <el-input v-model="dataForm.id" disabled />
        </el-form-item>

        <el-form-item label="归属门店" prop="storeId">
          <el-select
            v-model="dataForm.storeId"
            clearable
            style="width: 200px"
            class="filter-item"
            placeholder="请选择门店">
            <el-option v-for="(item,index) in storeList" :key="index" :label="item.storeName" :value="item.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="绑定优惠" prop="userId">
          <el-radio-group v-model="rewardType" @change="rewardTypeChange">
            <el-radio label="2">奖励商品</el-radio>
            <el-radio label="1">奖励现金</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-show="rewardType === '1'" prop="amount" label="输入奖励现金">
          <el-input v-model="dataForm.amount" >
            <template slot="append">元</template>
          </el-input>
        </el-form-item>

        <el-form-item v-show="rewardType === '2'" label="选择商品" prop="spuId">
          <el-autocomplete
            v-model="dataForm.spuTitle"
            :fetch-suggestions="querySearchGoodsName"
            :trigger-on-focus="false"
            style="width:300px"
            placeholder="请输入商品信息"
            @select="handleSelectSku"
          >
            <template slot-scope="{ item }">
              <div class="name" style="color:green">{{ item.goodName }}</div>
            </template>
          </el-autocomplete>
        </el-form-item>
        <el-form-item v-if="dataForm.storeSkuid" label="商品信息" prop="goods">
          <el-item v-if="dataForm.storeSkuid"><span style="color:#F56C6C;">{{ chooseGoodinfo.goodName }}&nbsp;&nbsp;&nbsp;原价：{{ (chooseGoodinfo.storePrice / 100).toFixed(2) }}元&nbsp;&nbsp;&nbsp;条码：{{ chooseGoodinfo.barCode }}</span></el-item>
        </el-form-item>
        <el-form-item label="绑定用户" prop="userId">
          <el-radio-group v-model="searchType" @change="searchTypeChange">
            <el-radio label="2">按手机搜索</el-radio>
            <el-radio label="1">按昵称搜索</el-radio>
          </el-radio-group>
          <el-autocomplete
            v-model="dataForm.search"
            :fetch-suggestions="querySearchUserNameOrPhone"
            :trigger-on-focus="false"
            :placeholder="searchInputPlaceholder"
            clearable
            style="width:300px"
            @select="handleSelect"
            @clear="clearNewPhoneSelect"
          >
            <template slot-scope="{ item }">
              <div class="name" style="color:green">{{ item.id }} {{ item.nickname }}<template><el-tag v-if="item.phone" size="medium"> {{ item.phone }}</el-tag></template></div>
            </template>
          </el-autocomplete>
          <el-row v-if="emptyNicknameFlag">
            <el-alert
              type="info"
              @close="closeAlert">
              <template slot="title">
                <el-row>未找到该手机号，你可以 </el-row>
                <el-row>1:尝试昵称搜索 </el-row>
                <el-row>2:<el-button type="text" size="small" @click="addNewUserPhone">绑定手机号</el-button></el-row>
              </template>
            </el-alert>
          </el-row>
          <el-row v-if="emptyPhoneFlag">
            <el-alert
              type="info">
              <template slot="title">
                <el-row>未找到该昵称</el-row>
              </template>
            </el-alert>
          </el-row>
          <el-input v-model="dataForm.userId" type="hidden"/>
        </el-form-item>
        <el-form-item v-if="dataForm.phoneFlag" label="手机号" prop="phone">
          <el-item v-if="dataForm.phone && !dataForm.newPhoneFlag"><span style="color:#F56C6C;">{{ dataForm.phone }}</span></el-item>
          <el-input v-if="dataForm.newPhoneFlag" v-model="dataForm.newPhone" clearable placeholder="请输入手机号" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="卡号" prop="cardNo">
          <el-item>{{ dataForm.cardNo }}</el-item>
        </el-form-item>
        <el-form-item label="卡密" prop="cardSecret">
          <el-item>{{ dataForm.cardSecret }}</el-item>
        </el-form-item>
        <el-form-item label="卡金额" prop="money">
          <el-item>{{ dataForm.money }}</el-item>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">确定</el-button>
        <el-button v-else type="primary" @click="updateData">绑定</el-button>
      </div>
    </el-dialog>
    <!-- 用户绑定手机号 -->
    <el-dialog
      :visible.sync="phoneDialogVisible"
      :title="phoneTitle"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      :show-close="false"
      width="40%"
      center>
      <div slot="title" class="header-title">
        <el-row>
          <el-col :span="18" style="font-size:16px;">
            <i style="color:#409EFF;" class="el-icon-info"/>
            <span>{{ phoneTitle }}</span>
          </el-col>
        </el-row>

      </div>
      <el-form
        ref="phoneFrom"
        :rules="phoneRules"
        :model="phoneDataForm"
        status-icon
      >
        <el-form-item prop="phone">
          <el-input v-model="phoneDataForm.phone" clearable placeholder="请输入手机号" autocomplete="off"/>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closePhoneForm">取 消</el-button>
        <el-button type="primary" @click="submitphoneForm('phoneFrom')">绑 定</el-button>
      </span>
    </el-dialog>

    <!-- 会员卡激活 -->
    <el-dialog :title="cardTitle" :visible.sync="activationCard">
      <el-form
        ref="activationForm"
        :model="activationForm"
        status-icon
        label-position="left"
        label-width="100px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="卡号" prop="cardNo">
          <el-input v-model="activationForm.cardNo" clearable placeholder="请填写要创建的卡号"/>
        </el-form-item>
        <el-form-item label="激活奖励" prop="userId">
          <el-radio-group v-model="rewardType" @change="rewardTypeChange">
            <el-radio label="2">奖励商品</el-radio>
            <el-radio label="1">奖励现金</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-show="rewardType === '1'" prop="amount" label="输入奖励现金">
          <el-input v-model="activationForm.amount" >
            <template slot="append">元</template>
          </el-input>
        </el-form-item>

        <el-form-item v-show="rewardType === '2'" label="选择商品" prop="spuId">
          <el-autocomplete
            v-model="dataForm.spuTitle"
            :fetch-suggestions="querySearchGoodsName"
            :trigger-on-focus="false"
            style="width:300px"
            placeholder="请输入商品信息"
            @select="handleSelectSku"
          >
            <template slot-scope="{ item }">
              <div class="name" style="color:green">{{ item.goodName }}</div>
            </template>
          </el-autocomplete>
        </el-form-item>

        <el-form-item v-if="activationForm.storeSkuid" label="商品信息" prop="goods">
          <el-item v-if="activationForm.storeSkuid"><span style="color:#F56C6C;">{{ chooseGoodinfo.goodName }}&nbsp;&nbsp;&nbsp;原价：{{ (chooseGoodinfo.storePrice / 100).toFixed(2) }}元&nbsp;&nbsp;&nbsp;条码：{{ chooseGoodinfo.barCode }}</span></el-item>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="offWindows()">取消</el-button>
        <el-button type="primary" @click="activation">确定</el-button>
      </div>
    </el-dialog>
    <!-- 会员卡修改金额 -->
    <el-dialog :title="updateMoneyTitle" :visible.sync="updateMoneyAlertStatus">
      <el-form
        ref="activationForm"
        :model="activationForm"
        status-icon
        label-position="left"
        label-width="100px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="卡金额" prop="money">
          <el-input v-model="activationForm.money" clearable placeholder=""/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="updateMoneyAlertStatus = false">取消</el-button>
        <el-button type="primary" @click="udpateMoney">确定</el-button>
      </div>
    </el-dialog>
    <!-- 会员卡批量操作 -->
    <el-dialog :title="cardBatchTitle" :visible.sync="cardBatchWindowStatus">
      <el-form
        ref="cardBatchData"
        :model="cardBatchData"
        status-icon
        label-position="left"
        label-width="100px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="归属门店" prop="storeId">
          <el-select
            v-model="cardBatchData.storeId"
            clearable
            style="width: 200px"
            class="filter-item"
            placeholder="请选择门店"
            @change="changeOrderStoreId(shipForm)" >
            <el-option v-for="(item,index) in storeList" :key="index" :label="item.storeName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="会员卡区间（开始）" prop="cardStart">
          <el-input v-model="cardBatchData.startCard" clearable placeholder="开始"/>
        </el-form-item>
        <el-form-item label="会员卡区间（结束）" prop="cardEnd">
          <el-input v-model="cardBatchData.endCard" clearable placeholder="结束"/>
        </el-form-item>
      </el-form>
      <el-button @click="offWindows()">取消</el-button>
      <el-button type="primary" @click="cardBatchWindowCommit">确定</el-button>
    </el-dialog>
  </div>
</template>

<style>
.el-table .cell {
  white-space: pre-line;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #20a0ff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
.avatar {
  width: 120px;
  height: 120px;
  display: block;
}
</style>

<script>
import { save, del, update, active, getExcelInfo, activationCard, updateCard, cardBatchUpdate } from '@/api/usercard'
import { detailCard } from '@/api/card'
import { searchUser } from '@/api/user'
import { searchStoreGoods } from '@/api/goods'
import Pagination from '@/components/Pagination'

export default {
  name: 'UserCard',
  components: { Pagination },
  filters: {
    formatStatus(status) {
      if (status === 0) {
        return '冻结'
      } else if (status === 1) {
        return '未使用'
      } else if (status === 2) {
        return '已使用'
      } else if (status < 0) {
        return '已过期'
      } else {
        return '错误状态'
      }
    }
  },
  data() {
    return {
      statusMap: [{ value: 0, name: '冻结' }, { value: 1, name: '已激活' }, { value: 2, name: '已使用' }],
      list: undefined,
      total: 0,
      listLoading: true,
      cardId: this.$route.query.cardId,
      listQuery: {
        pageNo: 1,
        limit: 25,
        cardNo: undefined,
        status: undefined,
        cardId: this.$route.query.cardId,
        cardStatus: undefined
      },
      rewardType: '2',
      phone: undefined,
      excelDataList: [],
      card: {},
      options: [],
      cardStatusMap: [{ value: 0, name: '冻结' }, { value: 1, name: '激活' }, { value: '2', name: '已使用' }],
      userInfo: [],
      listQuerystore: {
        status: 1
      },
      cardCount: 0,
      cardTitle: '创建会员卡号并激活该卡',
      updateMoneyTitle: '修改会员卡金额',
      updateMoneyAlertStatus: false,
      dataForm: {
        id: undefined,
        userId: undefined,
        cardNo: undefined,
        description: undefined,
        cardSecret: 0,
        money: 0,
        status: 1,
        search: undefined,
        phone: undefined,
        phoneFlag: false,
        newPhoneFlag: false,
        newPhone: undefined,
        storeId: undefined,
        spuTitle: undefined,
        amount: undefined,
        storeSkuid: undefined
      },
      chooseGoodinfo: undefined,
      cardBatchWindowStatus: false,
      activationForm: {
        id: undefined,
        cardNo: undefined,
        money: undefined,
        storeId: undefined,
        amount: undefined,
        spuTitle: undefined,
        storeSkuid: undefined
      },
      dialogFormVisible: false,
      activationCard: false,
      dialogStatus: '',
      goodsInfo: undefined,
      textMap: {
        update: '编辑',
        create: '创建'
      },
      rules: {},
      phoneRules: {
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' }, { pattern: /^1[3456789]\d{9}$/, message: '请输入正确电话' }
        ]
      },
      searchType: '2',
      searchInputPlaceholderMap: {
        '1': '请输入呢称搜索',
        '2': '请输入手机搜索'
      },
      searchInputPlaceholder: '请输入呢称搜索',
      cardBatchTitle: '会员卡批量操作',
      phoneDialogVisible: false,
      phoneTitle: undefined,
      phoneDataForm: {
        phone: undefined
      },
      emptyNicknameFlag: false,
      emptyPhoneFlag: false,
      cardBatchData: {
        startCard: undefined,
        endCard: undefined,
        storeId: undefined
      }
    }
  },
  watch: {
    'dataForm.newPhone': {
      handler(newVal, oldVal) {
        const that = this
        that.$set(that.dataForm, 'phone', newVal)
      },
      immediate: true,
      deep: true
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listStoresByPara()
      this.listLoading = true
      detailCard(this.listQuery)
        .then(response => {
          if (response.data.data.items.length < 1) {
            this.listLoading = false
            return
          }
          response.data.data.items.forEach(item => {
            item.money = item.money / 100
          })
          response.data.data.money = response.data.data.money / 100
          this.card = response.data.data
          this.list = response.data.data.items
          this.cardCount = response.data.data.total
          this.listLoading = false
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
    handleFilter() {
      this.getList()
    },
    resetForm() {
      this.dataForm = {
        id: undefined
      }
    },
    closePhoneForm() {
      const that = this
      that.phoneDialogVisible = false
      that.$set(that.dataForm, 'phone', that.phoneDataForm.phone)
      that.$set(that.dataForm, 'newPhone', that.phoneDataForm.phone)
    },
    closeAlert() {
      const that = this
      that.temptyNicknameFlag = false
      that.dataForm.phoneFlag = false
      that.$set(that.dataForm, 'phone', '')
    },
    handleSelect: function(item) {
      const that = this
      that.phoneDialogVisible = false
      that.dataForm.phoneFlag = false
      that.$set(that.dataForm, 'newPhoneFlag', false)
      that.dataForm.userId = item.id
      if (that.searchType === '1') {
        if (!item.phone || item.phone === '') {
          that.$set(that.phoneDataForm, 'phone', '')
          if (that.dataForm.phone) {
            that.$set(that.phoneDataForm, 'phone', that.dataForm.phone)
          }
          this.phoneTitle = '用户[' + item.nickname + ']需要手机号才可以绑定卡'
          that.dataForm.nickname = item.nickname
          that.phoneDialogVisible = true
        } else {
          that.dataForm.phoneFlag = true
          that.$set(that.dataForm, 'nickname', item.nickname)
          that.dataForm.phone = item.phone
          that.$set(that.phoneDataForm, 'phone', item.phone)
        }
      } else if (that.searchType === '2') {
        if (item.phone && item.phone.trim !== '') {
          that.dataForm.phoneFlag = true
          that.dataForm.phone = item.phone
          that.dataForm.nickname = item.nickname
        }
      }
    },
    clearNewPhoneSelect() {
      const that = this
      that.$set(that.dataForm, 'newPhoneFlag', false)
      that.$set(that.dataForm, 'phoneFlag', false)
      that.$set(that, 'emptyNicknameFlag', false)
      that.$set(that, 'emptyPhoneFlag', false)
      that.$set(that.dataForm, 'userId', '')
      that.$set(that.dataForm, 'phone', '')
      that.$set(that.dataForm, 'newPhone', '')
      that.$set(that.dataForm, 'nickname', '')
      that.$set(that.phoneDataForm, 'phone', '')
    },
    selectNewPhone() {
      const that = this
      that.$set(that.dataForm, 'newPhoneFlag', true)
      that.$set(that, 'emptyNicknameFlag', false)
      that.$set(that.dataForm, 'phoneFlag', false)
      if (!that.dataForm.phone) {
        that.$set(that.dataForm, 'phone', '')
        that.$set(that.dataForm, 'phoneFlag', false)
      } else {
        that.$set(that.dataForm, 'phoneFlag', true)
        if (that.dataForm.search || that.dataForm.nickname) {
          that.$set(that.dataForm, 'phoneFlag', false)
        }
      }
      if (that.searchType === '1') {
        if (that.dataForm.nickname) {
          const i = { 'nickname': that.dataForm.nickname, 'phone': '' }
          that.handleSelect(i)
        }
      } else {
        if (!that.dataForm.search && !that.dataForm.nickname) {
          that.$set(that.dataForm, 'phoneFlag', false)
        }
      }
    },
    submitphoneForm(formName) {
      const that = this
      that.$set(that.dataForm, 'newPhoneFlag', false)
      this.$refs[formName].validate((valid) => {
        if (valid) {
          searchUser({ phone: that.phoneDataForm.phone }).then(response => {
            if (response.data.data && response.data.data.length > 0) {
              this.$notify.info({
                title: '系统提示',
                message: '手机号已被绑定'
              })
              return
            }
            that.dataForm.phoneFlag = true
            that.dataForm.phone = that.phoneDataForm.phone
            that.phoneDialogVisible = false
          })
        } else {
          return
        }
      })
    },
    querySearchUserNameOrPhone: function(queryString, cb) {
      const that = this
      var query = {}
      that.phoneFlag = false
      if (that.searchType === '1') {
        query.nickname = queryString
        query.phone = ''
      } else {
        query.nickname = ''
        query.phone = queryString
      }
      that.$set(that, 'emptyNicknameFlag', false)
      that.$set(that.dataForm, 'newPhoneFlag', false)
      that.$set(that.dataForm, 'phoneFlag', false)
      that.$set(that, 'emptyPhoneFlag', false)
      searchUser(query)
        .then(res => {
          that.userInfo = res.data.data
          if (that.searchType === '2' && that.userInfo && that.userInfo.length === 0) {
            that.$set(that, 'emptyNicknameFlag', true)
          } else if (that.searchType === '1' && that.userInfo && that.userInfo.length === 0) {
            that.$set(that, 'emptyPhoneFlag', true)
          }
          for (const i of this.userInfo) {
            if (that.searchType === '1') {
              i.value = i.nickname
            } else {
              i.value = i.nickname
            }
          }
          cb(this.userInfo)
        })
        .catch(() => {
          this.$notify.error({
            title: '失败',
            message: '没有此用户'
          })
        })
    },

    handleStatus(row) {
      this.resetForm()
      this.dataForm.id = row.id
      this.dataForm.status = row.status === 1 ? 2 : 1
      active(this.dataForm)
        .then(res => {
          this.$notify.success({
            title: '成功',
            message: '充值成功'
          })
          this.getList()
        })
        .catch(() => {
          this.$notify.error({
            title: '失败',
            message: '失败'
          })
        })
    },
    handleShow(row) {
      this.$message({
        type: 'success',
        message: row.cardSecret
      })
    },
    updateMoneyAlert(row) {
      this.updateMoneyAlertStatus = true
      this.activationForm.id = row.id
      this.activationForm.money = row.money
    },
    udpateMoney() {
      const request = {
        id: this.activationForm.id,
        money: this.activationForm.money * 100
      }
      updateCard(request)
        .then(response => {
          this.activationCard = false
          this.getList()
        })
        .catch(
          response => {
            this.$notify.error({
              title: '修改金额失败',
              message: '修改金额失败'
            })
          }
        )
    },
    openActivation(row) {
      this.activationCard = true
      this.activationForm.id = row.id
      this.activationForm.cardNo = row.cardNo
      this.activationForm.storeId = row.storeId
    },
    activation() {
      if (this.activationForm.amount) {
        this.activationForm.amount = (this.activationForm.amount * 100).toFixed(0)
      }
      const request = {
        id: this.activationForm.id,
        cardNo: this.activationForm.cardNo,
        storeId: this.dataForm.storeId,
        storeSkuId: this.activationForm.storeSkuid,
        amount: this.activationForm.amount
      }
      if (!this.dataForm.storeId) {
        this.$notify.info({
          title: '系统提示',
          message: '请选择门店'
        })
        return
      }
      if (!this.activationForm.cardNo) {
        this.$notify.info({
          title: '系统提示',
          message: '请输入卡号'
        })
        return
      }
      activationCard(request)
        .then(response => {
          this.activationCard = false
          this.getList()
        })
        .catch(
          response => {
            this.$notify.error({
              title: '激活失败',
              message: '激活失败'
            })
          }
        )
    },
    searchTypeChange(value) {
      const that = this
      this.searchInputPlaceholder = this.searchInputPlaceholderMap[value]
      this.$set(this.dataForm, 'search', '')
      that.$set(that.dataForm, 'phone', '')
      that.$set(that.dataForm, 'phoneFlag', false)
      that.$set(that, 'emptyPhoneFlag', false)
      that.emptyNicknameFlag = false
      if (value === '2') {
        that.dataForm.newPhoneFlag = false
        that.dataForm.phoneFlag = false
        that.$set(that.dataForm, 'phone', '')
        that.$set(that.dataForm, 'newPhone', '')
      }
    },
    addNewUserPhone() {
      const that = this
      that.dataForm.phoneFlag = true
      that.$set(that.dataForm, 'phone', '')
      that.$set(that.dataForm, 'newPhone', '')
      that.dataForm.newPhoneFlag = true
      that.$set(that, 'emptyNicknameFlag', false)
    },
    handleCreate() {
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.refreshOptions()
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      save(this.dataForm)
        .then(response => {
          this.getList()
          this.dialogFormVisible = false
          this.$notify.success({
            title: '成功',
            message: '创建成功'
          })
        })
        .catch(response => {
          this.$notify.error({
            title: '失败',
            message: '失败'
          })
        })
    },
    handleUpdate(row) {
      this.dataForm = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.activationForm.storeId = row.storeId
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      const that = this
      if (!this.dataForm.storeId) {
        this.$notify.info({
          title: '系统提示',
          message: '请选择门店'
        })
        return
      }
      if (!this.dataForm.phone) {
        this.$notify.info({
          title: '系统提示',
          message: '请先绑定用户手机'
        })
        return
      } else {
        console.log(that.dataForm.phone)
        if (!(/^1[3456789]\d{9}$/.test(this.dataForm.phone))) {
          this.$notify.info({
            title: '系统提示',
            message: '请检查手机号格式'
          })
          return
        } else {
          searchUser({ phone: that.dataForm.phone }).then(response => {
            if (response.data.data && response.data.data.length > 0) {
              this.$notify.info({
                title: '系统提示',
                message: '手机号已被绑定'
              })
              return
            }
          })
        }
      }
      if (this.dataForm.amount) {
        // this.dataForm.amount = (this.dataForm.amount * 100).toFixed(0)
        that.$set(that.dataForm, 'amount', (that.dataForm.amount * 100).toFixed(0))
      }
      console.log(this.dataForm)
      update(that.dataForm)
        .then(response => {
          this.getList()
          this.dialogFormVisible = false
          this.$notify.success({
            title: '成功',
            message: '绑定成功'
          })
        })
        .catch(response => {
          this.$notify.error({
            title: '失败',
            message: '失败'
          })
        })
    },
    handleRead(row) {
      this.dataForm = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.refreshOptions()
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        del(row)
          .then(response => {
            this.$notify.success({
              title: '成功',
              message: '删除成功'
            })
            const index = this.list.indexOf(row)
            this.list.splice(index, 1)
          })
          .catch(response => {
            this.$notify.error({
              title: '失败',
              message: '失败'
            })
          })
      }).catch(() => {
        return false
      })
    },
    // 选择条件下载
    downExcelBtn() {
      this.downloadLoading = true
      const dataInfo = Object.assign({}, {
        cardId: this.$route.query.cardId
      })
      getExcelInfo(dataInfo).then(response => {
        if (response.data.data == null) {
          this.$notify.error({
            title: '失败',
            message: '没有信息可以导出'
          })
        }
        var data = response.data.data
        for (var i = 0; i < data.length; i++) {
          var temp = data[i]
          const obj = {}
          obj.cardNo = temp.cardNo
          obj.cardSecret = temp.cardSecret
          obj.title = temp.title
          var copy = Object.assign({}, obj)
          this.excelDataList.push(copy)
        }
        this.handleDownload(this.excelDataList)
        this.excelDataList = []
        this.downloadLoading = false
      })
        .catch(response => {
          this.downloadLoading = false
          this.$notify.error({
            title: '失败',
            message: response.data.errmsg
          })
        })
    },
    handleDownload(data) {
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = [
          '卡介绍',
          '卡号',
          '卡密'
        ]
        const filterVal = [
          'title',
          'cardNo',
          'cardSecret'
        ]
        excel.export_json_to_excel2(tHeader, data, filterVal, '卡信息')
      })
    },
    nextPage() {
      if (this.listQuery.cardNo !== '' && this.listQuery.cardNo !== null && this.listQuery.cardNo !== undefined) {
        return
      }
      if ((this.listQuery.pageNo <= (this.cardCount / this.listQuery.limit))) {
        this.listQuery.pageNo = (parseInt(this.listQuery.pageNo) + 1)
        this.getList()
      }
    },
    previousPage() {
      if (this.listQuery.cardNo !== '' && this.listQuery.cardNo !== null && this.listQuery.cardNo !== undefined) {
        return
      }
      if (this.listQuery.pageNo === 1) {
        return
      }
      this.listQuery.pageNo = (parseInt(this.listQuery.pageNo) - 1) < 0 ? 1 : (parseInt(this.listQuery.pageNo) - 1)
      this.getList()
    },

    cardBatchWindow() {
      this.cardBatchWindowStatus = true
    },
    cardBatchWindowCommit() {
      if (this.cardBatchData.startCard > this.cardBatchData.endCard) {
        this.$notify.error({
          title: '失败',
          message: '请确认开始结束单号'
        })
      }
      cardBatchUpdate(this.cardBatchData)
        .then(response => {
          if (response.data.data > 0) {
            this.$notify.info({
              title: '成功',
              message: '批量修改成功'
            })
            this.offWindows()
            return
          }
          this.$notify.error({
            title: '失败',
            message: '批量修改失败'
          })
          this.offWindows()
        })
        .catch(() => {
          this.$notify.error({
            title: '失败',
            message: '批量修改失败'
          })
          this.offWindows()
        })
    },
    offWindows() {
      const that = this
      this.getList()
      this.cardBatchWindowStatus = false
      this.activationCard = false
      that.$set(that.dataForm, 'amount', '')
      that.$set(that.activationForm, 'amount', '')
      that.$set(that.dataForm, 'spuTitle', '')
      that.$set(that.dataForm, 'storeSkuid', '')
      that.$set(that.activationForm, 'storeSkuid', '')
      that.$set(that.activationForm, 'spuTitle', '')
    },
    querySearchGoodsName: function(queryString, cb) {
      if (!this.dataForm.storeId) {
        this.$notify.error({
          title: '注意',
          message: '请先选择门店'
        })
        return
      }
      const requrst = {
        title: this.dataForm.spuTitle,
        storeId: parseInt(this.dataForm.storeId)
      }
      searchStoreGoods(requrst)
        .then(res => {
          this.goodsInfo = res.data.data
          for (const i of this.goodsInfo) {
            i.value = i.goodName
          }
          cb(this.goodsInfo)
        })
        .catch(() => {
          this.$notify.error({
            title: '失败',
            message: '查询不到商品'
          })
        })
    },
    handleSelectSku: function(item) {
      this.dataForm.storeSkuid = item.storeSkuid
      this.activationForm.storeSkuid = item.storeSkuid
      this.activationForm.storeId = this.dataForm.storeId
      this.chooseGoodinfo = item
    },
    // 奖励商品  或  奖励现金
    rewardTypeChoose: function() {
    },
    rewardTypeChange(value) {
      const that = this
      if (value === '1') {
        this.rewardType = '1'
        that.$set(that.dataForm, 'spuTitle', '')
        that.$set(that.dataForm, 'storeSkuid', '')
        that.$set(that.activationForm, 'storeSkuid', '')
        that.$set(that.activationForm, 'spuTitle', '')
      }
      if (value === '2') {
        this.rewardType = '2'
        that.$set(that.dataForm, 'amount', '')
        that.$set(that.activationForm, 'amount', '')
      }
    }
  }
}
</script>

